package com.yiboshi.rehrs.manager;

import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Slf4j
public class IptablesManager {

    // 检查是否有执行 iptables 命令的权限
    public static boolean checkPermissions() {
        try {
            Process process = Runtime.getRuntime().exec("iptables -L");
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (Exception e) {
           log.error("检查权限失败: " + e.getMessage());
            return false;
        }
    }

    // 开启 80 端口
    public static boolean openPort80() {
        try {
            //iptables -D INPUT ! -i lo -p tcp --dport 80 -j DROP
            //删除禁止规则
            if(isPort80Open()){
                executeCommand("iptables -D INPUT -p tcp --dport 80 -j DROP");
            }
            // 添加允许 80 端口的规则
            executeCommand("iptables -A INPUT -p tcp --dport 80 -j ACCEPT");
            
            // 保存规则（适用于 CentOS/RHEL）
            executeCommand("service iptables save");
            
            // 或使用 Debian/Ubuntu 的保存命令
            // executeCommand("netfilter-persistent save");
            
            log.info("80 端口已成功开启");
            return true;
        } catch (Exception e) {
           log.error("开启 80 端口失败: " + e.getMessage());
            return false;
        }
    }

    // 关闭 80 端口
    public static boolean closePort80() {
        try {
            // 先检查规则是否存在
            if (isPort80Open()) {


                // 删除允许 80 端口的规则
                executeCommand("iptables -D INPUT -p tcp --dport 80 -j ACCEPT");
                
                // 添加拒绝 80 端口的规则
                executeCommand("iptables -A INPUT -p tcp --dport 80 -j DROP");
                
                // 保存规则
                executeCommand("service iptables save");
                log.info("80 端口已成功关闭");
                return true;
            } else {
                log.info("80 端口已经处于关闭状态");
                return true;
            }
        } catch (Exception e) {
           log.error("关闭 80 端口失败: " + e.getMessage());
            return false;
        }
    }

    // 检查 80 端口是否开启
    public static boolean isPort80Open() {
        try {
            Process process = Runtime.getRuntime().exec("iptables -L INPUT -n");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("tcp") && line.contains("dpt:80") && line.contains("ACCEPT")) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
           log.error("检查 80 端口状态失败: " + e.getMessage());
            return false;
        }
    }

    // 执行系统命令
    private static void executeCommand(String command) throws IOException, InterruptedException {
        log.info("执行命令: " + command);
        Process process = Runtime.getRuntime().exec(command);
        
        // 获取命令输出
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String s;
        log.info("命令输出:");
        while ((s = stdInput.readLine()) != null) {
            log.info(s);
        }

        // 打印错误信息（如果有）
        StringBuilder errorMessage = new StringBuilder();
        while ((s = stdError.readLine()) != null) {
            errorMessage.append(s).append("\n");
        }
        
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new IOException("命令执行失败，错误码: " + exitCode + "\n" + errorMessage.toString());
        }
    }

    public static void main(String[] args) {
        // 检查权限
        if (!checkPermissions()) {
           log.error("错误: 执行此操作需要 root 权限");
            return;
        }

        // 示例：开启 80 端口
        if (openPort80()) {
            log.info("80 端口开启成功");
        } else {
            log.info("80 端口开启失败");
        }

        // 示例：检查 80 端口状态
        log.info("80 端口当前状态: " + (isPort80Open() ? "开启" : "关闭"));

        // 示例：关闭 80 端口
        if (closePort80()) {
            log.info("80 端口关闭成功");
        } else {
            log.info("80 端口关闭失败");
        }
    }
}